package com.example.passwordmanager;

import android.os.Bundle;
import android.text.TextUtils;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.Ohuang.ilivedata.MyLiveData;
import com.example.passwordmanager.databinding.ActivityMainBinding;
import com.example.util.base_util.SPUtil;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    ActivityMainBinding activityMainBinding;
    private Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        MyLiveData.getInstance().clear("startFg");
        MyLiveData.getInstance().with("startFg", Fragment.class).observe(this, new Observer<Fragment>() {
            @Override
            public void onChanged(Fragment fragment) {

                startFragment(fragment);
            }
        });
        fragment=getSupportFragmentManager().findFragmentById(R.id.frame_main);

        if (fragment==null) {
            showFirstFragment();
        }

    }

    private void startFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_main, fragment).commit();
    }

    private void showFirstFragment() {
        String s = (String) SPUtil.get(this, "password", "");
        if (TextUtils.isEmpty(s)) {
            getSupportFragmentManager().beginTransaction().
                    add(R.id.frame_main, new SetPasswordFragment()).
                    commit();

        } else {
            boolean b = (boolean) SPUtil.get(this, "isLock", false);
            if (!b) {
                getSupportFragmentManager().beginTransaction().
                        add(R.id.frame_main, new LoginFragment()).
                        commit();
            } else {
                long l = (long) SPUtil.get(this, "time", 0L);
                if (System.currentTimeMillis() > l + 3600 * 1000 * 24) {
                    getSupportFragmentManager().beginTransaction().
                            add(R.id.frame_main, new SetPasswordFragment()).
                            commit();
                    SPUtil.put(this, "password", "");//清空密码
                    SPUtil.put(this, "isLock", false);//解除锁定
                } else {
                    getSupportFragmentManager().beginTransaction().
                            add(R.id.frame_main, new LockFragment()).
                            commit();
                }


            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}